package com.example.hzq.zqb.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.example.hzq.zqb.R;
import com.example.hzq.zqb.bean.EnterpriseBean;
import com.example.hzq.zqb.adapter.EnterpriseAdapter;
import com.example.hzq.zqb.adapter.NetworkImageHolderView;
import com.example.hzq.zqb.model.Model;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.util.Arrays;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.example.hzq.zqb.fragment.Fragment1.imageurl;

/**
 * Created by hzq on 2017/7/11.
 */

public class EnterpriseFragment1 extends Fragment implements View.OnClickListener{
    private View view=null;
    private Context context;
    private int page=1,lastVisibleItemPosition;
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager manager;
    private ConvenientBanner convenientBanner;
    private List<String> networkImages;
    private EnterpriseAdapter enterpriseAdapter;
    private List<EnterpriseBean> list=null;
    private String[] image={imageurl + "company1.jpg",imageurl + "company2.jpg",imageurl + "company3.jpg",imageurl + "company4.jpg"};
    private Button bt1,bt2,pop1,pop2,pop3,pop4,pop5,pop6;
    private View popview,popview2;
    private PopupWindow popupWindow,popupWindow2;

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        page=1;
        view = inflater.inflate(R.layout.enterprise_f1, container, false);
        context = getActivity();
        convenientBanner = (ConvenientBanner) view.findViewById(R.id.enterconven);
        netinit();
        recyclerView=(RecyclerView)view.findViewById(R.id.enter_recycler);
        bt1=(Button)view.findViewById(R.id.paixu);
        bt2=(Button)view.findViewById(R.id.fangwei);
        bt1.setText("综合排序");
        bt2.setText("全城市");
        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        manager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        enterpriseAdapter =new EnterpriseAdapter(context);
        enterpriseAdapter.setList(list);
        Model model=new Model();
        Call<List<EnterpriseBean>> call=model.getEnterpriseList(page);
        call.enqueue(new Callback<List<EnterpriseBean>>() {
            @Override
            public void onResponse(Call<List<EnterpriseBean>> call, Response<List<EnterpriseBean>> response) {
                if(response.isSuccessful()&&response.body()!=null)
                {
                    list=response.body();
                    enterpriseAdapter.setList(list);
                }else{
                    Toast.makeText(context,"获取资源失败", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<List<EnterpriseBean>> call, Throwable t) {
                Toast.makeText(context,"404.enterfragment",Toast.LENGTH_SHORT).show();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition + 1 == list.size()) {
                    page+=1;
                    Model model=new Model();
                    Call<List<EnterpriseBean>> call=model.getEnterpriseList(page);
                    call.enqueue(new Callback<List<EnterpriseBean>>() {
                        @Override
                        public void onResponse(Call<List<EnterpriseBean>> call, Response<List<EnterpriseBean>> response) {
                            if(response.isSuccessful()&&response.body()!=null)
                            {
                                list.addAll(response.body());
                                enterpriseAdapter.setList(list);
                            }else{
                                Toast.makeText(context,"获取资源失败", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<List<EnterpriseBean>> call, Throwable t) {
                            Toast.makeText(context,"404.enter2",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItemPosition=list.size()-1;
            }
        });
        recyclerView.setAdapter(enterpriseAdapter);
        showPopwindow1();
        showPopwindow2();
        return view;
    }
    private void initImageLoader(){
        //网络图片例子,结合常用的图片缓存库UIL,你可以根据自己需求自己换其他网络图片库
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().
                showImageForEmptyUri(R.drawable.ic_default_adimage)
                .cacheInMemory(true).cacheOnDisk(true).build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context.getApplicationContext()).defaultDisplayImageOptions(defaultOptions)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }
    private void netinit() {
        initImageLoader();
        networkImages = Arrays.asList(image);
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages).setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused}).startTurning(2000);
    }
    private void showPopwindow1() {
        popview = LayoutInflater.from(context).inflate(
                R.layout.enterprisepop, null);
        pop1=(Button)popview.findViewById(R.id.e_pop_1);
        pop2=(Button)popview.findViewById(R.id.e_pop_2);
        pop3=(Button)popview.findViewById(R.id.e_pop_3);
        pop1.setText("综合排序");
        pop2.setText("最新发布");
        pop3.setText("离我最近");
        popupWindow = new PopupWindow(popview,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画
        popupWindow.setAnimationStyle(R.style.contextMenuAnim);
        //popupWindow隐藏时恢复屏幕正常透明度
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params=getActivity().getWindow().getAttributes();
                params.alpha=1f;
                getActivity().getWindow().setAttributes(params);
            }
        });
        pop1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    bt1.setText(pop1.getText().toString());
                    popupWindow.dismiss();

            }
        });
        pop2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    bt1.setText(pop2.getText().toString());
                    popupWindow.dismiss();

            }
        });
        pop3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    bt1.setText(pop3.getText().toString());
                    popupWindow.dismiss();
            }
        });
    }
    private void showPopwindow2() {
        popview2 = LayoutInflater.from(context).inflate(
                R.layout.enterprisepop2, null);
        pop4=(Button)popview2.findViewById(R.id.e_pop_4);
        pop5=(Button)popview2.findViewById(R.id.e_pop_5);
        pop6=(Button)popview2.findViewById(R.id.e_pop_6);
        pop4.setText("全城市");
        pop5.setText("分城区");
        pop6.setText("各街道");
        popupWindow2 = new PopupWindow(popview2,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow2.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow2.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow2.setOutsideTouchable(true);
        //设置可以点击
        popupWindow2.setTouchable(true);
        //进入退出的动画
        popupWindow2.setAnimationStyle(R.style.contextMenuAnim);
        //popupWindow隐藏时恢复屏幕正常透明度
        popupWindow2.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params=getActivity().getWindow().getAttributes();
                params.alpha=1f;
                getActivity().getWindow().setAttributes(params);
            }
        });
        pop4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    bt2.setText(pop4.getText().toString());
                    popupWindow2.dismiss();

            }
        });
        pop5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    bt2.setText(pop5.getText().toString());
                    popupWindow2.dismiss();

            }
        });
        pop6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    bt2.setText(pop6.getText().toString());
                    popupWindow2.dismiss();

            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.paixu:
                WindowManager.LayoutParams params=getActivity().getWindow().getAttributes();
                params.alpha=0.5f;
                getActivity().getWindow().setAttributes(params);
                popupWindow.showAtLocation(popview, Gravity.CENTER, 0, 0);
                break;
            case R.id.fangwei:
                WindowManager.LayoutParams params1=getActivity().getWindow().getAttributes();
                params1.alpha=0.5f;
                getActivity().getWindow().setAttributes(params1);
                popupWindow2.showAtLocation(popview2, Gravity.CENTER, 0, 0);
                break;
        }
    }
}
